<template>
  <div class="search-container">
    <form class="search-form" action="/">
      <van-search
        v-model="searchContent"
        show-action
        background="#0094ff"
        placeholder="请输入搜索关键词"
        @search="onSearch(searchContent)"
        @cancel="onCancel"
        @focus="isSearch = false"
      />
    </form>
    <SearchResult v-if="isSearch" :searchContent="searchContent"></SearchResult>
    <SearchSuggest
      v-else-if="searchContent"
      @doSearch="onSearch"
      :searchContent="searchContent"
    ></SearchSuggest>
    <SearchHistory
      v-else
      :searchHistotyList="searchHistotyList"
      @del="delHistory"
      @dosearch="onSearch"
    ></SearchHistory>
  </div>
</template>
<script>
import SearchResult from '@/views/search/components/searchResult.vue'
import SearchHistory from '@/views/search/components/searchHistory.vue'
import SearchSuggest from '@/views/search/components/searchSuggest.vue'
import { setItem, getItem } from '@/utils/storage.js'
export default {
  name: 'Search',
  data () {
    return {
      searchContent: '',
      isSearch: false,
      searchHistotyList: getItem('searchHistory') || []
    }
  },
  components: { SearchResult, SearchHistory, SearchSuggest },
  methods: {
    onSearch (sug) {
      this.isSearch = true
      this.searchContent = sug
      // 搜索历史记录
      // const index = this.searchHistotyList.findIndex((item) => item === sug)
      const index = this.searchHistotyList.indexOf(sug)
      if (index !== -1) {
        this.searchHistotyList.splice(index, 1)
      }
      this.searchHistotyList.unshift(sug)
    },
    onCancel () {
      this.isSearch = false
      this.$router.push('/')
    },
    delHistory (isDelAll, index) {
      isDelAll && (this.searchHistotyList = [])
      this.searchHistotyList.splice(index, 1)
    }
  },
  watch: {
    searchHistotyList: {
      immediate: true,
      handler (newVal) {
        setItem('searchHistory', newVal)
      }
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .search-form {
    position: fixed;
    z-index: 999;
    top: 0;
    left: 0;
    right: 0;
  }
  .van-search__action {
    color: #fff;
  }
}
</style>
